<?php

namespace app\api\service\cms;

use app\admin\model\cms\Platepost;
use app\admin\model\cms\Video;
use app\admin\model\Investment;
use app\admin\model\User;
use Redis;

/**
 * 缓存服务
 * Class CacheService
 */
class CacheService
{

    //添加hash缓存
    public function addHashData($table_name,$id){
        $redis = new Redis();    //返回redis对象
        $redis->connect('127.0.0.1', 6379);

        switch ($table_name){
            case 'plate_post'://论坛
                $data = Platepost::where('id', $id)->with(['user'])->find();
                if (!$data['user']) {
                    $data['user'] = User::getSoftDeleteUser($data['user_id']);
                }

                break;
            case 'investment'://投研日志
                $data = Investment::where('id', $id)->find();
                break;
            case 'video'://视频
                $data = Video::where('id', $id)->with(['user'])->find();
                if (!$data['user']) {
                    $data['user'] = User::getSoftDeleteUser($data['user_id']);
                }
                break;
        }
        if (!$data){
            return 0;
        }

        $this->delHashData($table_name, $id);//删除
        $res = $redis->hSet($table_name, $id, json_encode($data,JSON_UNESCAPED_UNICODE));//添加
        return json_encode($data,JSON_UNESCAPED_UNICODE);
    }

    //查询单个
    public function showHashData($table_name,$id){

        $redis = new Redis();    //返回redis对象
        $redis->connect('127.0.0.1', 6379);

//        $this->delHashData($table_name,$id);
//        dd(123);

        $res = $redis->hGet($table_name, $id);
        if ($res) {
            return json_decode($res, true);
        } else {
             $add = $this->addHashData($table_name,$id);
            if ($add){
                return json_decode($add, true);
            }else{
                return false;
            }
        }
    }

    //删除hash缓存
    public function delHashData($table_name,$id){
        $redis = new Redis();    //返回redis对象
        $redis->connect('127.0.0.1', 6379);
        $redis->hDel($table_name, $id);
        return true;
    }
}